package com.smh.myreflect2;

import com.smh.myreflect1.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class ConstructorDemo1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

//        Class类中用于获取构造方法的方法
//Constructor<?>[] getconstructors()
//Constructor<?>[] getDeclaredconstructors()
//Constructor<T> getConstructor(class<?>... parameterTypes)
//Constructor<T> getDeclaredconstructor(class<?>... parameterTypes)
//Constructor类中用于创建对象的方法
// T newInstance(object... initargs)
// setAccessible(boolean flag)
        Class<?> c = Class.forName("com.smh.myreflect1.Student");

        //获取public构造方法
        Constructor[] cons = c.getConstructors();
        for (Constructor con : cons) {
            System.out.println(con);
        }
        //获取所有的构造方法
        Constructor[] cons2 = c.getDeclaredConstructors();
        for (Constructor con : cons2) {
            System.out.println(con);
        }
        System.out.println("----------------");

        //获取一个
        //只能获取公共的
        Constructor con1 = c.getConstructor(String.class, int.class, String.class);//写参数
        System.out.println(con1);

        Constructor con2 = c.getDeclaredConstructor(String.class, int.class);
        System.out.println(con2);

        //获取权限修饰符
        //规律:public为1,static为0,private为2,其实就是位左移,这样运算块
        int modifiers = con2.getModifiers();
        System.out.println(modifiers);

        //获取参数
        Parameter[] parameters = con2.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter);
        }
        System.out.println("---------------");

        //创建对象
        //只能受用公共的构造方法,不然会报错
        Student student = (Student) con1.newInstance("zhangsna", 12, "nan");
        System.out.println(student);
        //如果你非要创建,暴力反射
        con2.setAccessible(true);//临时取消权限校验
        Student student1 = (Student) con2.newInstance("zhangsna", 12);
        System.out.println(student1);


    }
}
